package top.seekincs.service;

import org.springframework.stereotype.Service;
import top.seekincs.entity.AlumniUserEntity;
import top.seekincs.repository.AlumniUserRepository;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class AlumniUserService {

    final AlumniUserRepository alumniUserRepository;

    public AlumniUserService(AlumniUserRepository alumniUserRepository) {
        this.alumniUserRepository = alumniUserRepository;
    }

    public AlumniUserEntity addUser(String username, String password) {
        AlumniUserEntity userEntity = alumniUserRepository.findByUsernameAndPassword(username, password);
        if (Objects.isNull(userEntity)) {
            return alumniUserRepository.save(
                    AlumniUserEntity.builder()
                            .username(username)
                            .password(password)
                            .build()
            );
        }
        return null;
    }

    public AlumniUserEntity userExists(String username, String password) {
        return alumniUserRepository.findByUsernameAndPassword(username, password);
    }

    public AlumniUserEntity updateUser(AlumniUserEntity alumniUserEntity) {
        if (Objects.isNull(alumniUserEntity)) {
            return null;
        }
        Integer id = alumniUserEntity.getId();
        Optional<AlumniUserEntity> userEntity = alumniUserRepository.findById(id);
        if (userEntity.isPresent()) {
            return alumniUserRepository.save(alumniUserEntity);
        }
        return null;
    }

    public List<AlumniUserEntity> findAllAlumni(String username, String password) {
        AlumniUserEntity userEntity = alumniUserRepository.findByUsernameAndPassword(username, password);
        if (Objects.isNull(userEntity)) {
            return new ArrayList<>();
        }
        Integer schoolId = userEntity.getSchoolId();
        return alumniUserRepository.findAllBySchoolId(schoolId);
    }
}
